import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getArticleList, getAllCategories, getAllTags, createArticleApi, updateArticleApi, deleteArticleApi } from '@/api/article'
import type { Article, ArticleQuery } from '@/api/types'

export const useArticleStore = defineStore('article', () => {
  const articles = ref<Article[]>([])
  const total = ref(0)
  const categories = ref<string[]>([])
  const tags = ref<string[]>([])

  async function fetchArticles(params: ArticleQuery) {
    try {
      const response = await getArticleList(params)
      // 直接返回完整响应，让组件处理数据结构
      return response
    } catch (error) {
      console.error('Failed to fetch articles:', error)
      throw error
    }
  }

  async function fetchCategories() {
    try {
      const response = await getAllCategories()
      if (response?.data?.data) {
        categories.value = response.data.data
      } else {
        categories.value = []
        console.error('Invalid categories response:', response)
      }
    } catch (error) {
      console.error('Failed to fetch categories:', error)
      categories.value = []
      throw error
    }
  }

  async function fetchTags() {
    try {
      const response = await getAllTags()
      if (response?.data?.data) {
        tags.value = response.data.data
      } else {
        tags.value = []
        console.error('Invalid tags response:', response)
      }
    } catch (error) {
      console.error('Failed to fetch tags:', error)
      tags.value = []
      throw error
    }
  }

  async function createArticle(data: Partial<Article>) {
    const response = await createArticleApi(data)
    return response
  }

  async function updateArticle(data: Partial<Article>) {
    const response = await updateArticleApi(data)
    return response
  }

  async function deleteArticle(id: number) {
    const response = await deleteArticleApi(id)
    return response
  }

  return {
    articles,
    total,
    categories,
    tags,
    fetchArticles,
    fetchCategories,
    fetchTags,
    createArticle,
    updateArticle,
    deleteArticle
  }
})
